<?php
/**
 * Created by PhpStorm.
 * User: jocky
 * Date: 2017/7/20
 * Time: 下午4:17
 */

namespace common\models;

use common\models\ar\Templates;
use common\models\ar\TemplatesDetail;
use common\models\ar\User;
use common\models\ar\UserTrade;

class TemplateDao
{
    /**
     * 我的模板信息
     *
     * @param int $uid 代理或交易客户ID
     * @param int $type 1为代理，2为交易客户
     *
     * @return array
     */
    public static function my($uid, $type = 1)
    {
        if ($type == 1) {
            $obj = User::findOne($uid);
            $level = $obj->level;
        } else {
            $obj = UserTrade::findOne($uid);
            $level = $obj->level;
        }

        //模板中拥有的品种以及手续费信息
        $tmp = TemplatesDetail::find()->where(['template_id' => $obj->template_id])->asArray()->all();
        $templateDetail = [];
        foreach ($tmp as $v) {
            $templateDetail[$v['product']] = $v;
        }

        $levelInfo = Common::getLevelsInfo($level);
        $lists = [];
        $products = self::products();
        foreach ($products as $v) {
            $tmp = $v;
            if ($levelInfo['is_first']) {
                $tmp['trade_cost_open'] = 0;
                $tmp['trade_cost_close'] = 0;
            } else {
                if (!isset($templateDetail[$v['product']])) {
                    //模板中没有此品种
                    continue;
                }
                $tmp['trade_cost_open'] = $templateDetail[$v['product']]['trade_cost_open'];
                $tmp['trade_cost_close'] = $templateDetail[$v['product']]['trade_cost_close'];
            }
            $lists[$v['product']] = $tmp;
        }

        return $lists;
    }

    /**
     * 代理创建的模板记录
     * 如果为平台，显示所有代理的模板记录
     *
     * @param $uid
     * @param int $pageNo
     * @param int $pageSize
     *
     * @return array
     */
    public static function lists($uid, $pageNo = 1, $pageSize = 15)
    {
        $sql_count = "SELECT  COUNT(1) count FROM `templates` a ";
        $sql_lists = "SELECT a.*, b.`clientSN`,b.`alias` FROM  `templates` a ";
        $sql_where = '';
        $sql_orderBy = '';
        $sql_join = '';
        $sql_limit = '';
        $bind_arr = [];

        $tmpWhere = [];
        if ($uid != -1) {
            $tmpWhere[] = ' a.`uid` = :uid';
            $bind_arr[':uid'] = $uid;
        }
        $tmpWhere[] = ' a.`status` = 1';

        if (!empty($tmpWhere)) {
            $sql_where = " WHERE " . implode(' AND ', $tmpWhere);
        }

        $sql_join .= " LEFT JOIN `user` b ON a.`uid` = b.`uid`";
        $sql_orderBy .= " ORDER BY a.`time` DESC";
        $sql_limit .= " LIMIT " . ($pageNo - 1) * $pageSize . "," . $pageSize;

        $total = \Yii::$app->db->createCommand($sql_count . $sql_where, $bind_arr)->queryScalar();
        $lists = \Yii::$app->db->createCommand(
            $sql_lists . $sql_join . $sql_where . $sql_orderBy . $sql_limit,
            $bind_arr
        )->queryAll();

        return [
            'total' => $total,
            'lists' => $lists
        ];
    }


    /**
     * 添加模板
     * @param $base
     * @param $detail
     * @return bool
     */
    public static function add($base, $detail)
    {
        $time = time();
        $templateID = 0;
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            //模板记录
            if ($base['is_default'] == 1) {
                $sql = "UPDATE `templates` SET `is_default` = 0 WHERE `uid`=" . $base['uid'];
                \Yii::$app->db->createCommand($sql)->execute();
            }

            $sql = "INSERT INTO `templates` 
                      (`uid`,`is_default`,`title`,`desc`,`time`) 
                    VALUES 
                      (:uid,:is_default,:title,:desc,:time)
            ";
            \Yii::$app->db->createCommand(
                $sql,
                [
                    ':uid' => $base['uid'],
                    ':is_default' => $base['is_default'],
                    ':title' => $base['title'],
                    ':desc' => $base['desc'],
                    ':time' => $time,
                ]
            )->execute();

            //模板详情
            $templateID = \Yii::$app->db->getLastInsertID();
            if ($templateID < 10000) {
                //代理添加的模板从10000开始，交易监控后台控制小于10000
                $templateID = 10000;
                $sql = "UPDATE `templates` SET `id` = " . $templateID . " WHERE `id` = " . \Yii::$app->db->getLastInsertID();
                \Yii::$app->db->createCommand($sql)->execute();
            }

            $sql = "INSERT INTO `templates_detail` 
                      (`template_id`,`product`,`trade_cost_open`,`trade_cost_close`) 
                    VALUES 
            ";
            $arr = [];
            $info_extra = [];
            foreach ($detail as $v) {
                $arr[] = "($templateID,'" . $v['product'] . "'," . $v['trade_cost_open'] . "," . $v['trade_cost_close'] . ")";
                $info_extra[$v['product']] = [
                    '品种名称' => $v['product'],
                    '开仓手续费' => $v['trade_cost_open'],
                    '平仓手续费' => $v['trade_cost_close']
                ];
            }

            $sql .= implode(',', $arr);
            \Yii::$app->db->createCommand($sql)->execute();

            //操作历史
            $sql = "INSERT INTO `history_template_set` 
                      (`uid`,`template_id`,`direction`,`time`,`ip`,`ua`,`info`,`info_extra` )
                    VALUES 
                      (:uid,$templateID,1,$time,:ip,:ua,:info,:info_extra);
            ";
            $info = [
                '操作类型' => '新增模板',
                '是否为默认模板' => $base['is_default'] == 1 ? '是' : '否',
                '模板标题' => $base['title'],
                '模板描述' => $base['desc']
            ];

            \Yii::$app->db->createCommand(
                $sql,
                [
                    ':uid' => $base['uid'],
                    ':ip' => \Yii::$app->request->userIP,
                    ':ua' => \Yii::$app->request->userAgent,
                    ':info' => json_encode($info),
                    ':info_extra' => json_encode($info_extra)
                ]
            )->execute();

            $transaction->commit();
            $flag = true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            $flag = false;
        }

        if ($flag) {
            //如果是营业部，还需要通知到交易数据库
            $obj = User::findOne($base['uid']);
            $level = $obj->level;
            $levelInfo = Common::getLevelsInfo($level);
            if ($levelInfo['is_last'] == 1) {
                self::templateAddNotify($templateID);
            }
        }

        return $flag;
    }

    /**
     * 修改模板中的品种手续费
     *
     * @param $uid
     * @param $template_id
     * @param $detail
     * @return bool
     */
    public static function updateTradeCost($uid, $template_id, $detail)
    {
        $time = time();
        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $info_extra = [];
            foreach ($detail as $v) {
                $sql = "UPDATE `templates_detail` SET `trade_cost_open` = " . $v['trade_cost_open'] . ", `trade_cost_close` = " . $v['trade_cost_close'];
                $sql .= " WHERE `template_id` = " . $template_id . " AND `product` = '" . $v['product'] . "'";

                $tmp = [
                    '品种名称' => $v['product'],
                    '开仓手续费' => $v['trade_cost_open'],
                    '平仓手续费' => $v['trade_cost_close']
                ];
                $info_extra[] = $tmp;

                \Yii::$app->db->createCommand($sql)->execute();
            }

            //操作历史
            if (!empty($detail)) {
                $sql = "INSERT INTO `history_template_set` 
                          (`uid`,`template_id`,`direction`,`time`,`ip`,`ua`,`info`,`info_extra` )
                        VALUES 
                          (:uid,$template_id,3,$time,:ip,:ua,:info,:info_extra);
                ";

                \Yii::$app->db->createCommand(
                    $sql,
                    [
                        ':uid' => $uid,
                        ':ip' => \Yii::$app->request->userIP,
                        ':ua' => \Yii::$app->request->userAgent,
                        ':info' => json_encode(['修改品种手续费']),
                        ':info_extra' => json_encode($info_extra)
                    ]
                )->execute();
            }

            $transaction->commit();
            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            return false;
        }
    }

    /**
     * 获取模板详情
     *
     * @param $id
     * @param int $type 1获取模板基本信息和品种、手续费信息，2获取模板基本信息，3获取品种、手续费信息
     *
     * @return array
     */
    public static function info($id, $type = 1)
    {
        $return = [];
        if ($type == 1 || $type == 2) {
            $baseInfo = Templates::find()->where(['id' => $id])->asArray()->one();
            $return['base'] = $baseInfo;
        }

        if ($type == 1 || $type == 3) {
            $products = self::products();
            $lists = TemplatesDetail::find()->where(['template_id' => $id])->asArray()->all();
            $detail = [];
            foreach ($lists as $v) {
                $tmp = $v;
                foreach ($products[$v['product']] as $key => $val) {
                    if (array_keys($tmp, $key)) {
                        //键值有重复的情况
                        $tmp['product_' . $key] = $val;
                    } else {
                        $tmp[$key] = $val;
                    }

                }
                $detail[$v['product']] = $tmp;
            }
            $return['detail'] = $detail;
        }

        return $return;
    }

    /**
     * 获取所有品种信息
     */
    public static function products()
    {
        $db = \Yii::$app->db_options;
        $sql = "SELECT 
                  DISTINCT `product`
                FROM 
                  `instrument`
        ";
        $tmp = $db->createCommand($sql)->queryAll();
        $lists = [];
        foreach ($tmp as $v) {
            $lists[$v['product']] = $v;
        }

        return $lists;
    }

    /**
     * 同步写到交易数据库中
     *
     * @param $id
     * @return bool
     */
    public static function templateAddNotify($id)
    {
        $res = self::info($id, 1);
        $base = $res['base'];
        $detail = $res['detail'];
        //不存在
        if (!$base || !$detail) {
            return false;
        }

        $db = \Yii::$app->db_options;
        $sql = "INSERT INTO `user_commission_title` (`id`,`name`) VALUES (:id, :name)";
        $db->createCommand($sql, [
            ':id' => $base['id'],
            ':name' => $base['title'],
        ])->execute();

        $sql = "INSERT INTO `user_commission_detail` (
                  `title_id`, 
                  `productCode`, 
                  `chargeMode`, 
                  `openRatioByVolume`,
                  `closeRatioByVolume`,
                  `closeRatioTodayByVolume`
                ) VALUES 
        ";
        $rows = [];
        foreach ($detail as $v) {
            $rows[] = "(" . $v['template_id'] . ",'" . $v['product'] . "', 2, " . $v['trade_cost_open'] . ", " . $v['trade_cost_close'] . ", " . $v['trade_cost_close'] . ")";
        }
        $sql .= implode(',', $rows);
        if (!empty($rows)) {
            $db->createCommand($sql)->execute();
        }

        //通知表
        $sql = "INSERT INTO  `change_cache` (`userid`, `change_type`) VALUES (" . $base['id'] . ", 4)";
        $db->createCommand($sql)->execute();

        return true;
    }

    /**
     * 修改模板通知
     *
     * @param int $templateID 模板ID
     * @param int $type 1修改基本信息，2修改详细信息，3切换模板
     * @param int $uid 交易客户ID
     *
     * @return bool
     */
    public static function templateModifyNotify($templateID, $type = 1, $uid = 0)
    {
        $res = self::info($templateID, 1);
        $base = $res['base'];
        $detail = $res['detail'];
        //不存在
        if (!$base || !$detail) {
            return false;
        }

        $db = \Yii::$app->db_options;
        $transaction = $db->beginTransaction();
        try {
            switch ($type) {
                case 1:
                    //修改模板名称
                    $sql = "UPDATE `user_commission_title` SET `name` = :name WHERE `id` = :templateID";
                    $db->createCommand($sql, [':name' => $base['title'], ':templateID' => $base['id']])->execute();

                    //通知表
                    $sql = "INSERT INTO  `change_cache` (`userid`, `change_type`) VALUES (:templateID, 4)";
                    $db->createCommand($sql, [':templateID' => $base['id']])->execute();
                    break;
                case 2:
                    //修改模板详情
                    //先删除模板详情，再插入
                    $sql = "DELETE FROM `user_commission_detail` WHERE `title_id` = :templateID";
                    $db->createCommand($sql, [':templateID' => $base['id']])->execute();

                    $sql = "INSERT INTO `user_commission_detail` (
                              `title_id`, 
                              `productCode`, 
                              `chargeMode`, 
                              `openRatioByVolume`,
                              `closeRatioByVolume`,
                              `closeRatioTodayByVolume`
                            ) VALUES 
                    ";
                    $rows = [];
                    foreach ($detail as $v) {
                        $rows[] = "(" . $v['template_id'] . ",'" . $v['product'] . "', 2, " . $v['trade_cost_open'] . ", " . $v['trade_cost_close'] . ", " . $v['trade_cost_close'] . ")";
                    }

                    if (!empty($rows)) {
                        $sql .= implode(',', $rows);
                        $db->createCommand($sql)->execute();
                    }

                    //通知表
                    $sql = "INSERT INTO  `change_cache` (`userid`, `change_type`) VALUES (:templateID, 4)";
                    $db->createCommand($sql, [':templateID' => $base['id']])->execute();

                    break;
                case 3:
                    //分配新模板
                    //修改用户模板ID
                    $sql = "UPDATE `user` SET `commissionID` = :templateID WHERE `userID` = :uid";
                    $db->createCommand($sql, [':templateID' => $templateID, ':uid' => $uid])->execute();

                    //通知表
                    $sql = "INSERT INTO  `change_cache` (`userid`, `change_type`) VALUES (:uid, 5)";
                    $db->createCommand($sql, [':uid' => $uid])->execute();

                    break;
                default:
                    break;
            }

            $bool = true;
            $transaction->commit();
        } catch (\Exception $e) {
            $bool = false;
            $transaction->rollBack();
        }

        //@todo 如果操作失败，需要记录下来再次处理
        return $bool;
    }

    /**
     * 手续费模板切换判断
     *
     * @param $uidOperate
     * @param $uid
     * @param $templateID
     * @return array
     */
    public static function assignTemplateCheck($uidOperate, $uid, $templateID)
    {
        $errors = [];
        //模板信息
        $templateInfo = Templates::findOne($templateID);
        if (!$templateInfo || $templateInfo->uid != $uidOperate || $templateInfo->status != 1) {
            $errors[] = '您的手续费模板库中没有此模板';
            return $errors;
        }

        //模板详情
        $tmp = TemplatesDetail::find()->where(['template_id' => $templateID])->all();
        $tradeCostInfoOpen = [];
        $tradeCostInfoClose = [];
        foreach ($tmp as $v) {
            $tradeCostInfoOpen[$v->product] = $v->trade_cost_open;
            $tradeCostInfoClose[$v->product] = $v->trade_cost_close;
        }

        //判断该用户模板库中已存在的品种和手续费，是否满足此次切换的条件
        $tmp = Templates::find()->where(['uid' => $uid, 'status' => 1])->all();
        $ids = [];
        foreach ($tmp as $v) {
            $ids[] = $v->id;
        }

        if (!empty($ids)) {
            $productsInfo = TemplateDao::products();
            $sql = "SELECT 
                      `product`,
                      min(`trade_cost_open`)  min_trade_cost_open,
                      min(`trade_cost_close`) min_trade_cost_close
                    FROM 
                      `templates_detail` 
                    WHERE 
                      `template_id` IN (" . implode(',', $ids) . ")
                    GROUP BY `product`
            ";

            $tmp = \Yii::$app->db->createCommand($sql)->queryAll();
            foreach ($tmp as $v) {
                $tmpName = $productsInfo[$v['product']]['product'];
                if (!isset($tradeCostInfoOpen[$v['product']])) {
                    $str = "新的手续费模板中必须存在 ";
                    $str .= $tmpName;
                    $str .= "，且开仓手续费不能大于" . $v['min_trade_cost_open'];
                    $errors[] = $str;
                } else {
                    if ($tradeCostInfoOpen[$v['product']] > $v['min_trade_cost_open']) {
                        $str = "新的手续费模板中品种 ";
                        $str .= $tmpName;
                        $str .= " 的开仓手续费不能大于" . $v['min_trade_cost_open'];
                        $errors[] = $str;
                    }
                }

                if (!isset($tradeCostInfoClose[$v['product']])) {
                    $str = "新的手续费模板中必须存在 ";
                    $str .= $tmpName;
                    $str .= "，且平仓手续费不能大于" . $v['min_trade_cost_close'];
                    $errors[] = $str;
                } else {
                    if ($tradeCostInfoClose[$v['product']] > $v['min_trade_cost_close']) {
                        $str = "新的手续费模板中品种 ";
                        $str .= $tmpName;
                        $str .= " 的平仓手续费不能大于" . $v['min_trade_cost_close'];
                        $errors[] = $str;
                    }
                }
            }
        }
        return $errors;
    }
}
